//
//  TriMapViewController.swift
//  Matting
//  Created by JoyWT on 2022/3/4
//  
    

import UIKit
import opencv2

enum structType {
    case Cross, Rect, Ellipse
}
class TriMapViewController: BaseViewController {


    override func viewDidLoad() {
        super.viewDidLoad()


    }
    
    override func pickedDone() {
        let md = Mat(uiImage: originMaskImage!) //deeplab生成的mask图 ,黑色为前景区域
        //处理背景图片
        let nmd = Mat()
        Core.bitwise_not(src: md, dst: nmd) //对mask图片取反 白色为前景区域

        let trimap = trimap(mask: nmd, shape: .MORPH_CROSS, ksize: Size2i(width: 10, height: 10))
        imageView.image = trimap.toUIImage()
        
    }
    func trimap(mask: Mat, shape: MorphShapes, ksize:Size2i)->Mat{
        
        let tempMask = Mat()
        mask.copy(to: tempMask)
        let dilate = Mat()
        let k = Imgproc.getStructuringElement(shape: shape, ksize: ksize)
        Imgproc.dilate(src: mask, dst: dilate, kernel: k)
        
        let erode = Mat()
        Imgproc.erode(src: mask, dst: erode, kernel: k)
        
    
//        let bitwise_xor = Mat()
//        Core.bitwise_xor(src1: dilate, src2: erode, dst: bitwise_xor)
//
//
//        let gray = Mat()
//        Imgproc.threshold(src: bitwise_xor, dst: gray, thresh: 250 ,maxval: 128, type: .THRESH_BINARY)
//
//        let trimap = Mat()
//        Core.add(src1: gray, src2: erode, dst: trimap)
        
        let maskP = tempMask.dataPointer()
        let dilateP = dilate.dataPointer()
        let erodeP = erode.dataPointer()
        for index in 0...mask.total() {
            if dilateP[index] == 255 && erodeP[index] == 0 {
                maskP[index] = 128
            }
        }
        
        
        return tempMask
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}
